package com.fulihui.wgj.datastatis.api.impl.mass;

import com.alibaba.dubbo.config.annotation.Service;
import com.fulihui.common.builder.rpc.RpcResultBuilder;
import com.fulihui.common.conv.BeanConv;
import com.fulihui.common.result.rpc.BaseResult;
import com.fulihui.common.util.ConditionValidator;
import com.fulihui.common.util.DateUtils;
import com.fulihui.common.util.JsonConvertUtil;
import com.fulihui.wgj.datastatis.dal.domain.WxArticleTotalStat;
import com.fulihui.wgj.datastatis.dal.domain.WxArticleTotalStatDetail;
import com.fulihui.wgj.datastatis.dal.repository.ArticleTotalStatDetailRepository;
import com.fulihui.wgj.datastatis.dal.repository.ArticleTotalStatRepository;
import com.fulihui.wgj.datastatis.facade.api.mass.MassDataStatisApi;
import com.fulihui.wgj.datastatis.facade.dto.MassDataStatisDTO;
import com.fulihui.wgj.datastatis.facade.dto.MassDataStatisDetailDTO;
import com.fulihui.wgj.datastatis.facade.request.ArticleTotalStatDetailRequest;
import com.fulihui.wgj.datastatis.facade.request.ArticleTotalStatRequest;
import com.fulihui.wgj.datastatis.facade.request.MassDataStatisDetailRequest;
import com.fulihui.wgj.datastatis.facade.request.MassDataStatisPageRequest;
import com.fulihui.wgj.datastatis.facade.result.MassDataStatisDetailResult;
import com.fulihui.wgj.datastatis.facade.result.MassDataStatisPageResult;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import static com.fulihui.common.error.Errors.Commons.SAVE_FAILED;

/**
 * 图文数据统计RPC服务
 *
 * @author: Levon
 * @date: 2018-08-03 09:28
 */
@Component
@Service(interfaceClass = MassDataStatisApi.class, version = "1.0.0")
public class MassDataStatisApiImpl implements MassDataStatisApi {

    private static final Logger LOGGER = LoggerFactory.getLogger(MassDataStatisApiImpl.class);

    @Autowired
    private ArticleTotalStatRepository articleTotalStatRepository;

    @Autowired
    private ArticleTotalStatDetailRepository articleTotalStatDetailRepository;

    @Override
    public MassDataStatisPageResult queryMassDataStatisPage(MassDataStatisPageRequest request) {
        ConditionValidator.validate(request);

        PageInfo<WxArticleTotalStat> statPageInfo = articleTotalStatRepository.queryPageListByExample(buildPageQueryExample(request),
                request.getPage(), request.getRows());

        long total = statPageInfo.getTotal();
        MassDataStatisPageResult result = RpcResultBuilder.succPageResult(MassDataStatisPageResult.class,
                statPageInfo.getPageNum(), statPageInfo.getPageSize(), Math.toIntExact(total));
        if (total > 0) {
            List<MassDataStatisDTO> dataStatisDTOS = BeanConv.copy(statPageInfo.getList(), MassDataStatisDTO.class);
            result.setValues(dataStatisDTOS);
        }
        return result;
    }

    @Override
    public MassDataStatisDetailResult queryMassDataStatisDetail(MassDataStatisDetailRequest request) {
        Example example = new Example(WxArticleTotalStatDetail.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("msgid", request.getMsgid());
        criteria.andEqualTo("appId", request.getAppid());
        Date refDate = request.getRefDate();
        criteria.andGreaterThanOrEqualTo("statDate", refDate);
        criteria.andLessThanOrEqualTo("statDate", DateUtils.addDays(refDate, 6));
        List<WxArticleTotalStatDetail> statDetails = articleTotalStatDetailRepository.queryByExample(example);
        MassDataStatisDetailResult result = RpcResultBuilder.succ(MassDataStatisDetailResult.class);
        if (!CollectionUtils.isEmpty(statDetails)) {
            List<MassDataStatisDetailDTO> values = BeanConv.copy(statDetails, MassDataStatisDetailDTO.class);
            result.setValues(values);
        }
        return result;
    }

    /**
     * 组装条件
     *
     * @param request
     * @return
     */
    private Example buildPageQueryExample(MassDataStatisPageRequest request) {
        Example example = new Example(WxArticleTotalStat.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("appId", request.getAppId());
        if (StringUtils.isNotBlank(request.getTitle())) {
            criteria.andLike("title", "%" + request.getTitle() + "%");
        }
        if (request.getStartRefDate() != null) {
            criteria.andGreaterThanOrEqualTo("refDate", request.getStartRefDate());
        }
        if (request.getEndRefDate() != null) {
            criteria.andLessThanOrEqualTo("refDate", request.getEndRefDate());
        }
        example.orderBy("refDate").desc();
        return example;
    }

    /**
     * 保存
     *
     * @param request
     * @return
     */
    @Override
    public BaseResult saveArticleTotalStat(ArticleTotalStatRequest request) {

        Example example = new Example(WxArticleTotalStatDetail.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("msgid", request.getMsgid());
        criteria.andEqualTo("appId", request.getAppid());
        List<WxArticleTotalStat> stats = articleTotalStatRepository.queryByExample(example);
        if (!CollectionUtils.isEmpty(stats)) {
            LOGGER.info("已存在统计数据，不进行保存。msgid={},appid={}", request.getMsgid(), request.getAppid());
            return RpcResultBuilder.succ();
        }

        WxArticleTotalStat totalStat = new WxArticleTotalStat();
        totalStat.setAppId(request.getAppid());
        totalStat.setMsgid(request.getMsgid());
        totalStat.setTitle(request.getTitle());
        try {
            totalStat.setRefDate(DateUtils.parseWebFormat(request.getRefDate()));
        } catch (ParseException e) {
            LOGGER.error("日期转换错误", e);
        }
        totalStat.setGmtCreate(new Date());
        totalStat.setGmtModified(new Date());
        Integer count = articleTotalStatRepository.saveSelective(totalStat);
        return count > 0 ? RpcResultBuilder.succ() : RpcResultBuilder.fail(SAVE_FAILED);
    }

    /**
     * 保存
     *
     * @param request
     * @return
     */
    @Override
    public BaseResult saveArticleTotalStatDetail(ArticleTotalStatDetailRequest request) {

        Example example = new Example(WxArticleTotalStatDetail.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("msgid", request.getMsgid());
        criteria.andEqualTo("appId", request.getAppid());
        List<WxArticleTotalStatDetail> statDetails = articleTotalStatDetailRepository.queryByExample(example);
        if (!CollectionUtils.isEmpty(statDetails)) {
            LOGGER.info("已存在详细统计数据，不进行保存。msgid={},appid={}", request.getMsgid(), request.getAppid());
            return RpcResultBuilder.succ();
        }

        WxArticleTotalStatDetail statDetail = null;
        try {
            statDetail = JsonConvertUtil.underline2hump(request.getDetails(), WxArticleTotalStatDetail.class);
        } catch (IOException e) {
            LOGGER.error("json转换错误", e);
        }
        statDetail.setMsgid(request.getMsgid());
        statDetail.setAppId(request.getAppid());
        Integer count = articleTotalStatDetailRepository.saveSelective(statDetail);
        return count > 0 ? RpcResultBuilder.succ() : RpcResultBuilder.fail(SAVE_FAILED);
    }
}
